<template>
  <div>
    <div class="title">选择收货地址</div>
    <div v-for="address in addressList" :key="address.id" class="row">
     <el-radio v-model="addressId" :label="address.id" @change="addressChange">
        {{address.provinceName}}
        {{address.cityName}}
        {{address.districtName}}
        {{address.address}}
        ({{address.name}}收)
        {{address.mobile}}
      </el-radio>
      <div class="editTitle" @click="handleUpdate(address)">修改地址</div>
    </div>
    <el-button class="add" type="primary" size="mini" @click="handleAdd">使用其他地址</el-button>
    <el-dialog :title="textMap[formStatus]" :visible.sync="dialogFormVisible" append-to-body>
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="88px"
        style="margin: 0 50px;">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="temp.mobile" />
        </el-form-item>
        <el-form-item label="省市区" prop="city">
          <AddressCascader ref="addressCascader" v-model="selectedOptions" @selectAddressDetail="selectAddressDetail" />
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="temp.address" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" />
        </el-form-item>
        <el-form-item label="是否默认">
          <el-radio-group v-model="temp.isDefault">
            <el-radio v-for="item in isDefaultJson" :key="item.value" :label="item.value">
              {{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="saveData()">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addressPageByQo, addressSaveOrUpdate } from '@/api/company'
import AddressCascader from '@/components/AddressCascader'
export default {
  name: 'DeliveryAddress',
  props: {},
  components: {
    AddressCascader
  },
  data() {
    const validateCity = (rule, value, callback) => {
      if (!this.temp.districtId) {
        callback(new Error('请选择省市区'))
      } else {
        callback()
      }
    }
    return {
      addressList: [],
      addressId: '',
      temp: {
        id: 0,
        name: '',
        mobile: '',
        identifier: '',
        provinceId: '',
        provinceName: '',
        cityId: '',
        cityName: '',
        districtId: '',
        districtName: '',
        address: '',
        isDefault: 0
      },
      dialogFormVisible: false,
      rules: {
        name: [{ required: true, message: '请输入', trigger: 'change' }],
        mobile: [{ required: true, validator: this.$mobileValidator, trigger: 'blur' }],
        address: [{ required: true, message: '请输入', trigger: 'blur' }],
        city: [{ required: true, trigger: 'blur', validator: validateCity }]
      },
      selectedOptions: [],
      isDefaultJson: [
        { label: '否', value: 0 },
        { label: '是', value: 1 },
      ],
      formStatus: '',
      textMap: {
        update: '编辑地址',
        create: '添加地址'
      },
    }
  },
  computed: {},
  watch: {},
  methods: {
    // 获取收货地址
    getAddressList() {
      addressPageByQo().then((response) => {
        console.log(888, response);
        const { list } = response
        this.addressList = list
        if (this.addressId) {
          this.addressChange(this.addressId)
          return;
        }
        for (let i = 0; i < list.length; i++) {
          if (list[i].isDefault) {
            this.addressId = list[i].id
            this.addressChange(this.addressId)
            return
          }
          this.addressId = list[0] ? list[0].id : ''
          this.addressChange(this.addressId)
        }
      });
    },
    handleAdd() {
      this.resetTemp()
      this.selectedOptions = []
      this.formStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      if (this.temp.districtId) {
        this.selectedOptions = [this.temp.provinceId.toString(), this.temp.cityId.toString(), this.temp.districtId.toString()]
      } else {
        this.selectedOptions = []
      }
      this.formTitle = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    saveData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          delete this.temp.createTime
          addressSaveOrUpdate(this.temp, this.formStatus !== 'create').then(() => {
            this.getAddressList()
            this.dialogFormVisible = false

            this.$message({
              message: '保存成功',
              type: 'success'
            });
          })
        }
      })
    },
    addressChange(value) {
      this.$emit('updateAddress', value)
    },
    resetTemp() {
      this.temp = {
        id: 0,
        name: '',
        mobile: '',
        identifier: '',
        provinceId: '',
        provinceName: '',
        cityId: '',
        cityName: '',
        districtId: '',
        districtName: '',
        address: '',
        isDefault: 0
      }
    },
    selectAddressDetail(value) {
      if (value) {
        this.$set(this.temp, `provinceId`, value.provinceId)
        this.$set(this.temp, `provinceName`, value.provinceName)
        this.$set(this.temp, `cityId`, value.cityId)
        this.$set(this.temp, `cityName`, value.cityName)
        this.$set(this.temp, `districtId`, value.districtId)
        this.$set(this.temp, `districtName`, value.districtName)
      } else {
        this.$set(this.temp, `provinceId`, '')
        this.$set(this.temp, `provinceName`, '')
        this.$set(this.temp, `cityId`, '')
        this.$set(this.temp, `cityName`, '')
        this.$set(this.temp, `districtId`, '')
        this.$set(this.temp, `districtName`, '')
      }
    },
  },
  created() {
    this.getAddressList()
  },
  mounted() {
    
  },
  beforeCreate() {},
  beforeMount() {},
  beforeUpdate() {},
  updated() {},
  beforeDestroy() {},
  destroyed() {},
  activated() {},
}
</script>

<style lang='scss' scoped>
  .title {
    text-align: left;
    font-size: 15px;
  }

  .row {
    position: relative;
    margin-top: 10px;
    display: flex;
  }

  .add {
    text-align: left;
    margin-top: 10px;
  }

  .editTitle {
    position: absolute;
    line-height: 16px;
    vertical-align:middle;
    cursor: pointer;
    right: 0;
    
  }
</style>